from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional

from app.core.database import get_db
from app.core.deps import get_current_user, get_tenant_id
from app.schemas.dept import DeptCreate, DeptUpdate
from app.models.user import User
from app.services.dept import dept_service
from app.utils.response import ResponseUtil

router = APIRouter()


@router.get("/tree", summary="获取部门树")
async def get_department_tree(
    include_user_count: bool = Query(False, description="是否包含用户数量"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取部门树形结构"""
    try:
        tree = await dept_service.get_dept_tree(
            db=db,
            tenant_id=tenant_id,
            include_user_count=include_user_count
        )
        return ResponseUtil.success(data=tree)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取部门树失败: {str(e)}"
        )


@router.get("/", summary="获取部门列表")
async def get_departments(
    status_filter: Optional[bool] = Query(None, description="部门状态过滤"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取部门列表"""
    try:
        if keyword:
            # 搜索部门
            depts = await dept_service.search_depts(db=db, tenant_id=tenant_id, keyword=keyword)
        else:
            # 获取树形结构
            depts = await dept_service.get_dept_tree(
                db=db,
                tenant_id=tenant_id,
                include_user_count=True
            )
        return ResponseUtil.success(data=depts)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取部门列表失败: {str(e)}"
        )


@router.post("/", summary="创建部门")
async def create_department(
    dept_data: DeptCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """创建新部门"""
    try:
        dept = await dept_service.create_dept(
            db=db,
            obj_in=dept_data.model_dump(),
            tenant_id=tenant_id
        )
        return ResponseUtil.success(data=dept, message="部门创建成功")
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建部门失败: {str(e)}"
        )


@router.get("/{dept_id}", summary="获取部门详情")
async def get_department(
    dept_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """根据ID获取部门详情"""
    try:
        dept = await dept_service.get(db, id=dept_id)
        if not dept or dept.tenant_id != tenant_id:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )
        return ResponseUtil.success(data=dept)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取部门详情失败: {str(e)}"
        )


@router.put("/{dept_id}", summary="更新部门")
async def update_department(
    dept_id: int,
    dept_data: DeptUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """更新部门信息"""
    try:
        # 获取部门
        dept = await dept_service.get(db, id=dept_id)
        if not dept or dept.tenant_id != tenant_id:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )

        # 更新部门
        updated_dept = await dept_service.update_dept(
            db=db,
            db_obj=dept,
            obj_in=dept_data.model_dump(exclude_unset=True)
        )
        return ResponseUtil.success(data=updated_dept, message="部门更新成功")
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新部门失败: {str(e)}"
        )


@router.delete("/{dept_id}", summary="删除部门")
async def delete_department(
    dept_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """删除部门"""
    try:
        success = await dept_service.delete_dept(db=db, dept_id=dept_id, tenant_id=tenant_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )
        return ResponseUtil.success(message="部门删除成功")
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除部门失败: {str(e)}"
        )


@router.get("/{dept_id}/users", summary="获取部门用户")
async def get_department_users(
    dept_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
    tenant_id: str = Depends(get_tenant_id)
):
    """获取部门下的用户列表"""
    try:
        # 检查部门是否存在
        dept = await dept_service.get(db, id=dept_id)
        if not dept or dept.tenant_id != tenant_id:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="部门不存在"
            )

        users = await dept_service.get_dept_users(
            db=db, dept_id=dept_id, tenant_id=tenant_id
        )
        return ResponseUtil.success(data={
            "dept_id": dept_id,
            "dept_name": dept.dept_name,
            "users": users
        })
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取部门用户失败: {str(e)}"
        )